 function X_filtered = ecg_bandpass2(X,Fp,Rs,Samp_freq)
%% Bandpass filter for ECG
% Usage:
% X_filtered = ecg_bandpass(X);
% X_filtered = ecg_bandpass(X, [Fp1 Fp2]);
% X_filtered = ecg_bandpass(X, [Fp1 Fp2], Rs);
% X_filtered = ecg_bandpass(X, [Fp1 Fp2], Rs, Samp_freq);
%
% Inputs:
% X: Discrete time signal
% [Fs1,Fs2]: Stop band (notch) in Hz
% Rs: Maximiumm attenuation in the stop band (notch) in dB
% Samp_freq: Sampling frequency of the signalin Hz
% 
% Outputs:
% X_filtered: filtered signal
%
% Warnings:
% Do not overdesign the chebyshev type I filter; filtfilt() may fail if the filter order is larger than 5
%
% Debug mode:
% If output variable is not specified, debug mode will automatically turned on.
% Filtered signal and Frequencncy response of the notch filter will be drawn in new figure window.
%
% Copyright by Group 8

if(nargin < 4)
    Samp_freq=553.6;
end
if(nargin < 3)
    Rs=10;
end
if(nargin < 2)
    Fp= [0.5 40];
end


%Define filter requirements
% Adaptive filter implementation
%To ensure accurate heartbeat calculation without distortion
%2-step
%   1. To compare storage HR
%   2. To determine which is the best by not over the upper and lower limit
%

    %To ensure in range
        Wp = Fp / Samp_freq *2;
        Ws = [eps 60] / Samp_freq*2;
        Rp = 9;

        %generate cheby1 filter
        [n Wc] = cheb1ord(Wp,Ws,Rp,Rs);
        if(n>=5)
            display('Order n>=5, seems to overdesign bandpass filters');
        end

        [b,a]=cheby2(n,Rp,Wc);

        %filter signal
        X_filtered = filtfilt(b,a,X);
        

%Debug:
if(~nargout)
figure(1)
freqz(b,a,Samp_freq/2,1000);
figure(2);
t = (0:length(X)-1)/550;
subplot(2,1,1), plot(t,X,';Raw signal;'),xlim([15 25])
ylabel('Voltage / V')
subplot(2,1,2), plot(t,X_filtered,';Filtered signal;'),xlim([15 25])
xlabel('time / s');

end

